package com.template.web;

import com.template.model.User;
import com.template.service.UserService;
import com.template.util.RMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/unauth.action",method = RequestMethod.GET)
    public Map<String, Object> unauth(HttpServletResponse response) {
        return new RMap().put("code", 401).put("msg", "没有登录");
    }

    @ApiOperation(value = "查询所有用户", notes = "登录之后，查询所有用户")
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数没填好"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value = "/selectAll.action", method = RequestMethod.GET)
    public Map<String, Object> selectAll(HttpServletResponse response, HttpServletRequest request) {
        List<User> all = userService.list(null);
        return RMap.ok(all);
    }

    @PostMapping(value = "/login.action")
    public Map<String, Object> login(@RequestBody User user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsercode(), user.getUserpwd());
        RMap result = null;
        try {
            subject.login(token);
            result = RMap.ok();
            result.put("userInfo", subject.getPrincipal());
            result.put("toke", subject.getSession().getId());
        } catch (IncorrectCredentialsException e) {
            result = RMap.error("密码错误");
        } catch (LockedAccountException e) {
            result = RMap.error("登录失败，用户被冻结");
        } catch (AuthenticationException e) {
            result = RMap.error("用户名不存在");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping(value = "/logout.action")
    public boolean logout() {
        SecurityUtils.getSubject().logout();
        return true;
    }
}
